package com.example.demo.app.controller;

import java.util.List;
import java.util.function.Consumer;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.app.exception.ServiceException;
import com.example.demo.app.exception.UserNameNotMatchPasswordException;
import com.example.demo.app.model.Book;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableListMultimap.Builder;

@Controller
public class BookController {

	@GetMapping("/bookInfo")
	public ModelAndView bookInfo(@ModelAttribute("book") Book book) {
		ModelAndView bookView = new ModelAndView("book");
		bookView.addObject("name", "一个故事");
		bookView.addObject("publishDate", "2015-09-09");
		bookView.addObject("author", "hello");
		return bookView;
	}
	
	
	@GetMapping("exception/{sub}")
	public String except(@PathVariable("sub") Integer sub,Model map) {
		try {
			int a = 100 / sub;
			map.addAttribute("result", a);
			if(1 == sub) {
				throw new ServiceException("不能赋值 1");
			}
			
			if(2 == sub) {
				throw new UserNameNotMatchPasswordException();
			}
			if(3 == sub) {
				throw new RuntimeException();
			}
			return "test";
		}catch(ServiceException e) {
			throw e;
		}
	}
	
	@PostMapping("/addBook")
	public String addBook(@Validated Book book,BindingResult result, Model model) {
		System.out.println(book.toString());
		book.setAuthor("new_zhangsan");
		model.addAttribute("book", book);
		System.out.println(book.toString());
		if(result.hasErrors()){
			List<ObjectError> allErrors = result.getAllErrors();
			Builder<String, String> builder = ImmutableListMultimap.builder();
			allErrors.stream().forEach(new Consumer<ObjectError>() {

				@Override
				public void accept(ObjectError t) {
					builder.put(t.getObjectName(), t.getCode()+","+":"+t.getArguments()[0] + ":" + t.getDefaultMessage());
				}
			});
			
			model.addAttribute("result",builder.build());
		}else {
			model.addAttribute("result","success");
		}
		return "book";
	}
	
	
	
}
